package com.xqx.metool.util;

import org.springframework.util.StringUtils;

import javax.print.DocFlavor;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * sql 参数填充
 * @Author : xingquanxiang
 * @Date : 2021/12/16 15:32
 */
public class SqlBuildUtil {

    public static String sqlBuild(String sql,  String paramsText) {
        if (!StringUtils.hasText(sql) || !StringUtils.hasText(paramsText)) {
            return "参数异常！";
        }
        try {
            System.out.println("->" + DateUtils.now());
            System.out.println("原生sql：" + sql);
            System.out.println("sql参数：\n" + paramsText);
            paramsText = paramsText.replaceFirst("@", "");
            String[] params = paramsText.split("@");
            List<String> paramList = Arrays.stream(params).map(str -> str.split("\\[")[1].split("]")[0]).collect(Collectors.toList());
            Pattern pattern = Pattern.compile("^[0-9]+$");

            for (String param : paramList) {
                if (pattern.matcher(param).matches()) {
                    sql = sql.replaceFirst("\\?", "" + param + "");
                } else {
                    sql = sql.replaceFirst("\\?", "'" + param + "'");
                }
            }
            System.out.println("sql构建后：\n" + sql);
            return sql;
        }catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static String sqlNormalBuild(String sql,  String paramsText) {
        if (!StringUtils.hasText(sql) || !StringUtils.hasText(paramsText)) {
            return "参数异常！";
        }
        try {
            System.out.println("->" + DateUtils.now());
            System.out.println("普通原生sql：" + sql);
            System.out.println("sql参数：\n" + paramsText);
            String[] params = paramsText.split(",");
            Pattern pattern = Pattern.compile("^[0-9]+$");

            for (String param : params) {
                if (pattern.matcher(param).matches()) {
                    sql = sql.replaceFirst("\\?", "" + param + "");
                } else {
                    sql = sql.replaceFirst("\\?", "'" + param + "'");
                }
            }
            System.out.println("普通sql构建后：\n" + sql);
            return sql;
        }catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
